package com.book.iphone;

import com.book.book.domain.ApplyDO;
import com.book.book.domain.UsersDO;
import com.book.book.domain.WantSeeDO;
import com.book.book.service.ApplyService;
import com.book.book.service.UsersService;
import com.book.common.config.BootdoConfig;
import com.book.common.domain.FileDO;
import com.book.common.service.FileService;
import com.book.common.utils.DateUtils;
import com.book.common.utils.FileType;
import com.book.common.utils.FileUtil;
import com.book.common.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.lang.reflect.MalformedParameterizedTypeException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户上传图书（未审核）
 * 作者：青松
 * 日期： 2018/2/4
 */
@Controller
@RequestMapping("/iphone/contribute")
public class ContributeController {

    @Autowired
    private ApplyService applyService;

    @Autowired
    private FileService sysFileService;

    @Autowired
    private BootdoConfig bootdoConfig;
    @Autowired
    private UsersService usersService;
    @PostMapping("/apply")
    String apply(ApplyDO applyDO, HttpServletRequest request){
        String userid = null;
        UsersDO usersDO= (UsersDO)request.getSession().getAttribute("userInfo");
        if (usersDO != null){
            userid=usersDO.getOpenId();
        }else {
            return "redirect:/iphone/login";
        }

//        userid= (int) request.getSession().getAttribute("userid");
        applyDO.setUserId(userid);
        applyDO.setUpDate(new Date());
        applyDO.setIsPass(2);
        //判断用户是否已经贡献过这本书
        Map<String,Object> applyMap=new HashMap<>();
        applyMap.put("userId",userid);
        applyMap.put("bookName",applyDO.getBookName());
        List<ApplyDO> userapply=  applyService.list(applyMap);
        if (userapply.size()!=0){
            return "redirect:/iphone/listallapply/"+userid;
        }
        int aa =applyService.save(applyDO);
        if (aa==1){
            usersDO = usersService.getopenid(applyDO.getUserId());
            int a=usersDO.getBorrowNum()==null?1:usersDO.getBorrowNum()+1;
            usersDO.setBorrowNum(a);
            usersService.update(usersDO);
            request.getSession().setAttribute("userInfo",usersDO);
            return "redirect:/iphone/listallapply/"+userid;
        }else {
            return "book/phone/error";
        }
    }


    @ResponseBody
    @PostMapping("/upload")
    R upload(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        /*if ("test".equals(getUsername())) {
            return R.error(1, "请使用正式用户登录进行操作");
        }*/
        String fileName = file.getOriginalFilename();
        fileName = FileUtil.renameToUUID(fileName);
        // 文件路径
        String datdDirectory = "image_".concat(DateUtils.format(new Date(),"yyyy_MM_dd")+"/");
        File dest = new File(bootdoConfig.getUploadPath().concat(datdDirectory), fileName);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        FileDO sysFile = new FileDO(FileType.fileType(fileName), "/img/iphone/"+ datdDirectory + fileName, new Date());
        try {
            FileUtil.uploadFile(file.getBytes(), bootdoConfig.getUploadPath()+datdDirectory, fileName);
        } catch (Exception e) {
            return R.error();
        }
        if (sysFileService.save(sysFile) > 0) {
            return R.ok().put("fileName",sysFile.getUrl());
        }
        return R.error();
    }

}
